//
//  CartoonDViewController.m
//  A段项目,漫画
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "CartoonDViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
#import "UMSocial.h"
@interface CartoonDViewController ()<UMSocialUIDelegate>
@property(nonatomic, retain)cartoonDestai *myCartoonDes;
@property(nonatomic, retain)UITableView *myCartoonTableView;
@property(nonatomic, retain)UICollectionView *myFootView;
@property(nonatomic, retain)NSString *lastUpCID;
@property(nonatomic, copy)void (^myBlockLast)(NSString *cid);
@property(nonatomic, copy)void (^myBlockFirst)(NSString *cid);
@property(nonatomic, retain)NSMutableArray *saveCartoonIDArr;
@property(nonatomic, assign)BOOL issave;
@property(nonatomic, retain)UIAlertView *saveAlter;
@property(nonatomic, retain)UIAlertView *saveAlterFinish;
@property(nonatomic, assign)BOOL isFinishLoading;

//动画
@property(nonatomic, retain)UIView *witeView;
@property(nonatomic, retain)NSMutableArray *witeImageArr;
@property(nonatomic, retain)UIImageView *witeImageView;
@property(nonatomic, retain)UIProgressView *myProgress;
@property(nonatomic, retain)UILabel *myLabel;


@end

@implementation CartoonDViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.myCartoonDes = [[cartoonDestai alloc] init];
        self.saveCartoonIDArr = [NSMutableArray array];
        self.issave = NO;
        self.isFinishLoading = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createAvtivity];
    [self createWiteImage];
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    [self createData];
    [self createView];
    [self loadSaveCartoon];
    [self.view bringSubviewToFront:self.witeView];
    //播放动画
    [self.witeImageView startAnimating];
}
- (void)createWiteImage{
    self.witeImageArr = [NSMutableArray array];
    NSArray *names = @[@"735d4677ec7cdd522281cfbddd29ac71－1（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－2（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－3（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－4（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－5（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－6（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－7（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－8（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－9（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－10（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－11（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－12（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－13（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－14（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－15（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－16（被拖移）.tiff"];
    
    for (NSString *name in names) {
        UIImage *image = [UIImage imageNamed:name];
        [self.witeImageArr addObject:image];
    }
    self.witeImageView.animationImages = self.witeImageArr;
    //设置播放时间
    self.witeImageView.animationDuration = 0.5;
}
- (void)createAvtivity{
    self.witeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.witeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.witeView];
    [self.witeView release];
    
    CGFloat bili = 222.0 / 271;
    self.witeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 1.5, WIDTH / 1.5 * bili)];
    self.witeImageView.center = CGPointMake(WIDTH / 2, HEIGHT / 3);
    [self.witeView addSubview:self.witeImageView];
    [self.witeImageView release];
    
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 1.5, 30)];
    self.myLabel.center = CGPointMake(WIDTH / 2, HEIGHT / 3 + WIDTH / 1.5 * bili / 2 + 10);
    self.myLabel.text = @"loading..........";
    [self.witeView addSubview:self.myLabel];
    self.myLabel.textAlignment = NSTextAlignmentCenter;
    //    self.myProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(100, WIDTH - 50, 200, 30)];
    //    self.myProgress.center = CGPointMake(WIDTH / 2, HEIGHT / 2 - 10);
    //    [self.myProgress setProgressViewStyle:UIProgressViewStyleDefault];
}


//判断是否收藏
- (void)isSave{
    for (saveCartoon *save in self.saveCartoonIDArr) {
        if ([save.comic_id isEqualToString:self.myCartoonDes.comic_id]) {
            self.issave = YES;
        }
    }
}

- (void)createView{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(click)];
    
    self.myCartoonTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -35, WIDTH, HEIGHT - 49) style:UITableViewStyleGrouped];
    [self.view addSubview:self.myCartoonTableView];
    [self.myCartoonTableView release];
    self.myCartoonTableView.delegate = self;
    self.myCartoonTableView.dataSource = self;
//    self.myCartoonTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myCartoonTableView.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    //1.5比例
    flow.itemSize = CGSizeMake(WIDTH / 7, WIDTH / 7 / 1.5);
    //设置间距
    flow.minimumInteritemSpacing = 20;
    flow.minimumLineSpacing = 20;
    flow.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.myFootView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flow];
    self.myCartoonTableView.tableFooterView = self.myFootView;
    //注册cell
    [self.myFootView registerClass:[ChapterCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.myFootView.delegate = self;
    self.myFootView.dataSource = self;
    self.myFootView.backgroundColor = [UIColor whiteColor];
    [self.myFootView release];
    
    //block
    self.myBlockLast = ^(NSString *cid){
        chapter *cp = [self.myCartoonDes.myChapters firstObject];
        [self toReadCartoonVCWithComic_id:self.myCartoonDes.comic_id AndCid:cp.cid];
    };
    //block
    self.myBlockFirst = ^(NSString *cid){
        chapter *cp = [self.myCartoonDes.myChapters lastObject];
        [self toReadCartoonVCWithComic_id:self.myCartoonDes.comic_id AndCid:cp.cid];
    };
    
}

-(void)click
{
    NSLog(@"分享");
    
    NSString *str = self.myCartoonDes.cover_url;
    UIImage *shareImage = [UIImage imageNamed:str];
    NSString *shareText = self.myCartoonDes.title;
    NSString *shareURL = self.myCartoonDes.cover_url;
    NSString *share = [NSString stringWithFormat:@"%@ %@",shareText,shareURL];
    
     [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55406a3ce0f55a7bd5002d90" shareText:share shareImage:shareImage shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, nil] delegate:self];
    
}

//收藏动漫的协议方法

- (void)saveCartoon{
    if (!self.issave) {
        //打开数据库
        [[DataBaseHandle shareDB] openDB];
        //创建表
        [[DataBaseHandle shareDB] createCartoonTable];
        //插入id
        [[DataBaseHandle shareDB] insertCartoonWithID:self.myCartoonDes.comic_id PicUrl:self.myCartoonDes.cover_url AndTiTle:self.myCartoonDes.title];
        //    [self loadSaveCartoon];
        self.issave = YES;
        [self.myCartoonTableView reloadData];
        //关闭数据库
        [[DataBaseHandle shareDB] closeDB];
        
        [MidTools shareMidTools].addSave ++;
        [[MidTools shareMidTools].delegate10 upDate];
        self.saveAlterFinish = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [self.saveAlterFinish show];
    }else{
        self.saveAlter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏这个漫画" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [self.saveAlter show];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.myCartoonDes.myChapters.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ChapterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    chapter *cp = self.myCartoonDes.myChapters[indexPath.row];
    [cell.chapterButton setTitle:cp.seq_no forState:UIControlStateNormal];
    return cell;
}

//跳转方法
- (void)toReadCartoonVCWithComic_id:(NSString *)comic_id AndCid:(NSString *)cid{
    ReadCartoonViewController *readVC = [[ReadCartoonViewController alloc] init];
    readVC.comic_id = comic_id;
    readVC.cid = cid;
    readVC.PicUrl = self.myCartoonDes.cover_url;
    readVC.TiTle = self.myCartoonDes.title;
    
    readVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:readVC animated:YES];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    chapter *cp = self.myCartoonDes.myChapters[indexPath.row];
    [self toReadCartoonVCWithComic_id:self.myCartoonDes.comic_id AndCid:cp.cid];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        static NSString *reuse1 = @"reuse1";
        cartoonDestailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse1];
        if (cell == nil) {
            cell = [[cartoonDestailTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse1];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.delegate = self;
        cell.myBlock = self.myBlockFirst;
        UIImage *placeImage = [UIImage imageNamed:@"FOR@{XC4(JCI7}{P@Y]({{1－1（被拖移）.tiff"];
        NSURL *url = [NSURL URLWithString:self.myCartoonDes.cover_url];
        [cell.cartoonImage sd_setImageWithURL:url placeholderImage:placeImage options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        
        cell.title.text = self.myCartoonDes.title;
        cell.artist_name.text = [NSString stringWithFormat:@"作者:%@",self.myCartoonDes.artist_name];
        cell.type.text = [NSString stringWithFormat:@"类型:%@",self.myCartoonDes.type];
        cell.grade_ave.text = [NSString stringWithFormat:@"评分:%@",self.myCartoonDes.grade_ave];
        
        [self isSave];
        
        if(self.issave){
            [cell.saveButton setBackgroundImage:[UIImage imageNamed:@"iconfont-icon47ddd"] forState:UIControlStateNormal];
            NSLog(@"已收藏");
        }else{
            [cell.saveButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-2"] forState:UIControlStateNormal];
            NSLog(@"点击收藏");
        }
        
        return cell;
    }else if (indexPath.row == 1) {
        static NSString *reuse2 = @"reuse2";
        cartoonBrief_intrdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse2];
        if (cell == nil) {
            cell = [[cartoonBrief_intrdTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse2];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.brief_intrd.text = self.myCartoonDes.brief_intrd;
        return cell;
    }else if (indexPath.row == 2) {
        static NSString *reuse3 = @"reuse3";
        lastUPTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse3];
        if (cell == nil) {
            cell = [[lastUPTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse3];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.myBlock = self.myBlockLast;
        cell.update_date.text = [NSString stringWithFormat:@"更新时间:%@",self.myCartoonDes.update_date];
        chapter *cp = [self.myCartoonDes.myChapters firstObject];
        [cell.lastUpButton setTitle:cp.seq_no forState:UIControlStateNormal];
        if (self.isFinishLoading) {
            NSLog(@"结束动画");
            [self.witeImageView stopAnimating];
            [self.view bringSubviewToFront:self.myCartoonTableView];
        }
        return cell;
    }else{
        static NSString *reuse = @"reuse";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        CGFloat bili = 177.0 / 133;
        return WIDTH / 3 * bili + 40;
    }else if (indexPath.row == 1){
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        //根据文本大小(font)计算出文本的rect值,最大范围不超过(375,400)
        
        CGRect rect = [self.myCartoonDes.brief_intrd boundingRectWithSize:CGSizeMake(WIDTH, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 40;
    }else if (indexPath.row == 2){
        
        return WIDTH / 7 / 1.5 + 20;
    }else{
        return 200;
    }
}

//本地收藏解析
- (void)loadSaveCartoon{
    //打开数据库
    [[DataBaseHandle shareDB] openDB];
    //创建表
    [[DataBaseHandle shareDB] createCartoonTable];
    //查询Id
    self.saveCartoonIDArr = [[DataBaseHandle shareDB] selectSaveCartoon];
    NSLog(@"saveCartoonIDArr COUNT %ld",self.saveCartoonIDArr.count);
    //关闭数据库
    [[DataBaseHandle shareDB] closeDB];
}

//网络解析
- (void)createData{
    //字符串拼接
    NSString *cartoonSTR = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/ComicDetailForIos/comic_id/%@/page/1/listcnt/9999/uin/0/local_version/2.3.2/channel/1001/guest_id/921199FA-97DD-457B-80FA-5A7E1D0FC7BA",self.comic_id];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:cartoonSTR parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableDictionary *cartoonDic = dic[@"data"];
        [self.myCartoonDes setValuesForKeysWithDictionary:cartoonDic];
        NSMutableArray *chapters = cartoonDic[@"chapters"];
        for (NSMutableDictionary *chapterDic in chapters) {
            chapter *cp = [[chapter alloc] init];
            [cp setValuesForKeysWithDictionary:chapterDic];
            [self.myCartoonDes.myChapters addObject:cp];
            [cp release];
        }
        NSLog(@"%ld",self.myCartoonDes.myChapters.count);
        NSLog(@"数据解析成功");
        [self.myCartoonTableView reloadData];
        [self.myFootView reloadData];
        self.isFinishLoading = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"数据解析失败");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
